package com.service.Authorization.controller;

import com.service.Authorization.dto.CheckTenantDto;
import com.service.Authorization.dto.ScreenUserDto;
import com.service.Authorization.dto.TenantDto;
import com.service.Authorization.dto.UserSecret;
import com.service.Authorization.entity.ManageInfo;
import com.service.Authorization.entity.PortalUser;
import com.service.Authorization.service.ManageInfoService;
import com.service.Authorization.service.PortalUserService;
import com.service.config.annotation.LoginUser;
import com.service.config.utils.ModelMapperUtil;
import com.service.config.utils.RedisUtil;
import com.service.config.utils.Result;
import com.service.config.utils.UserTokenManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.service.config.constant.Constant.*;

/**
 * openApi用户表(PortalUser)表控制层
 *
 * @author makejava
 * @since 2021-08-10 16:14:28
 */
@RestController
@RequestMapping("portalUser")
@Api(value = "华为云管理openApi用户接口", tags = "华为云管理openApi用户接口")
public class PortalUserController {
    @Resource
    private ManageInfoService manageInfoService;
    @Resource
    private PortalUserService portalUserService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private ManageInfoService userInfoService;
    @PostMapping("checkApiAccount")
    @ApiOperation(value = "校验云管平台的账号和密码")
    @ResponseBody
    public Result checkTenant(@RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken,
                              @RequestBody CheckTenantDto checkTenantDto) {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                Map  check = manageInfoService.check(checkTenantDto, userId);
                if (check.containsKey("errorMsg")) {
                    return Result.builder().data(check).build();
                }
                return Result.builder().data(Collections.EMPTY_MAP).build();
            }else {
                return Result.builder().code(USERNAME_Off_SITE).msg(usernameOffSite).build();
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    @PostMapping("addApiAccount")
    @ApiOperation(value = "增加云管api账号和密码")
    @ResponseBody
    public Result addApiAccount(@RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken,
                                @RequestBody TenantDto tenantDto) throws Exception {

        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                List<PortalUser> screenUserList = portalUserService.insertOrUpdate(ModelMapperUtil.strictMap(tenantDto, PortalUser.class), userId);
                if (screenUserList != null) {
                    return Result.failure(CLOUD_CAMPUS_ACCOUNT_SAME, "云管理账号同域名已存在，是否覆盖");
                }
                return Result.ok();
            }else {
                return Result.failure(USERNAME_Off_SITE, usernameOffSite);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }
    @PostMapping("updateApiAccount")
    @ApiOperation(value = "更新云管的密码")
    @ResponseBody
    public Result updateApiAccount(@RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken,
                                   @RequestBody TenantDto tenantDto) {

        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                portalUserService.updateApiAccount(ModelMapperUtil.strictMap(tenantDto,PortalUser.class));
                return Result.ok();
            }else {
                return Result.failure(USERNAME_Off_SITE, usernameOffSite);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }
    @GetMapping("deleteApiAccount")
    @ApiOperation(value = "删除云管理api账号")
    @ResponseBody
    public Result deleteApiAccount(@RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken,
                                   @RequestParam("screen_id") @ApiParam("api账号id") String screen_id) {

        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                portalUserService.deleteById(screen_id);
                return Result.ok();
            }else {
                return Result.failure(USERNAME_Off_SITE, usernameOffSite);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }
    @GetMapping("enableAndDisable")
    @ApiOperation(value = "api账号的启用和禁用")
    @ResponseBody
    public Result enableAndDisable(@RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken,
                                   @RequestParam("screen_user_id") @ApiParam("大屏用户id") String screen_user_id,
                                   @ApiParam("状态：true-启用，false-禁用")@RequestParam("status") Boolean status,
                                   @ApiParam("域名")@RequestParam("domain") String domain) {

        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                portalUserService.serviceStatusBind(screen_user_id,status,userId,domain);
                return Result.ok();
            }else {
                return Result.failure(USERNAME_Off_SITE, usernameOffSite);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }
    @GetMapping("findAllApi")
    @ApiOperation(value = "云管账号列表")
    @ResponseBody
    public Result findAllApi(@RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                List<ScreenUserDto> screenUserList = portalUserService.queryAll(userId);
                return Result.ok().setData(screenUserList);
            }else {
                return Result.failure(USERNAME_Off_SITE, usernameOffSite);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }
    @GetMapping("findSecret")
    @ApiOperation(value = "查看密钥")
    @ResponseBody
    public Result findSecret(@RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                ManageInfo manageInfo = userInfoService.queryById(userId);
                return Result.ok().setData(ModelMapperUtil.strictMap(manageInfo, UserSecret.class));
            }else {
                return Result.failure(USERNAME_Off_SITE, usernameOffSite);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }
    @GetMapping("freshSecret")
    @ApiOperation(value = "刷新密钥")
    @ResponseBody
    public Result freshSecret(@RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                ManageInfo manageInfo = userInfoService.freshSecret(userId);
                return Result.ok().setData(ModelMapperUtil.strictMap(manageInfo, UserSecret.class));
            }else {
                return Result.failure(USERNAME_Off_SITE, usernameOffSite);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }
}
